package com.lws.framework.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;

public class WebUtil {

    private static SimpleDateFormat sdf;

    static {
        sdf = new SimpleDateFormat("yyyy-MM-dd");
        registerDateConvert();
    }

    public static <T> void DTO2Bean(final T bean, Object dto) {
        try {
            BeanUtils.copyProperties(bean, dto);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static void registerDateConvert() {
        ConvertUtils.register(new Converter() {
            @Override
            @SuppressWarnings("rawtypes")
            public Object convert(Class MyDateConvert, Object value) {
                if (value == null)
                    return null;
                if (!(value instanceof String))
                    throw new RuntimeException("Only String is supported");
                String str = (String) value;
                if (str.trim().equals(""))
                    return null;

                try {
                    return sdf.parse(str);
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
            }
        }, Date.class);
    }

}
